#include "uart2.h"
xdata u16 uart2_rx_sta;
xdata u8 uart2_buf[UART2_PACKET_MAX_LEN+2];
xdata u8 uart2_step;

void uart2_isr() interrupt 4
{	
	u8 res;
	if(RI0)
	{
		RI0=0;
		res=SBUF0;
		if(uart2_rx_sta&UART2_PACKET_OK)
			return;
		if(uart2_step==0)
		{
			if(res=='\r')
				uart2_step=1;
			else if(res=='\n')
				uart2_rx_sta |= UART2_PACKET_OK;
			else
			{
				if(uart2_rx_sta>=UART2_PACKET_MAX_LEN)
					uart2_rx_sta=0;
				uart2_buf[uart2_rx_sta++]=res;
			}
		}else if(uart2_step==1)
		{
			uart2_step=0;
			if(res=='\n')
				uart2_rx_sta |= UART2_PACKET_OK;
			else 
				uart2_rx_sta =0;
		}
	}
}


void uart2_init(u32 baud)
{
	MUX_SEL |= 0x40;
	P0MDOUT &= 0xCF;
	P0MDOUT |= 0x10;
	ADCON =0x80;
	
	SCON0 =0x50;
	PCON &= 0x7F;
	
	baud = 1024-(u16)(3225600.0f/baud);
	SREL0H = (baud>>8)&0xff;  
	SREL0L = baud&0xff;
	
	#if(UART2_INT_EN)
	{
		ES0=1;
		EA=1;
		uart2_rx_sta=0;
		uart2_step=0;
	}
	#else
		ES0=0;
	#endif
}

void uart2_send_byte(u8 byte)
{
	ES0=0;
	SBUF0=byte;
	while(!TI0)
	TI0=0;
	#if(UART2_INT_EN)
	{
		ES0=1;
	}
	#endif

}

void uart2_send_bytes(u8 *bytes,u16 len)
{
	u16 i;
	ES0=0;
	for(i=0;i<len;i++)
	{
		SBUF0=bytes[i];
		while(!TI0)
		TI0=0;
	}
	#if(UART2_INT_EN)
	{
		ES0=1;
	}
	#endif
}

char putchar(char c)
{
	uart2_send_byte(c);
	return c;
}





